import threading
import time,os

# 需求: 需要统计1-400000的数字中那些是素数? for循环实现
# 结果: python多线程需要时间197.32206010818481秒

def prime(num, quantity, lock):
    print(os.getpid(),os.getppid())
    start = (num-1)*quantity+1
    end = num*quantity+1
    for i in range(start, end):
        if i > 1:
            flag = True
            for j in range(2, i//2+1):
                if i % j == 0:
                    flag = False
                    break

            if flag:
                lock.acquire()
                count.append(i)
                lock.release()


if __name__ == "__main__":
    count = []
    start = time.time()
    lock = threading.Lock()
    cpuNum = 8
    quantity = 500
    for i in range(1, cpuNum+1):
        t = threading.Thread(
            target=prime, args=(i, quantity, lock))
        t.start()
        t.join()
    print("1-%r之间有%r个素数" % (cpuNum*quantity, len(count)))
    timer = time.time() - start
    print("程序执行时间: %r 秒" % timer)
